import Vue from 'vue'
import VueRouter from 'vue-router'
import userStore from '@/store/user'
// 引入进度条
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

import store from '@/store'
import routes from './routes.js'

Vue.use(VueRouter)
// 重写this.$router.push和this.$router.replace
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function (loaction, resolve, reject) {
  if (resolve && reject) {
    originalPush.call(this, loaction, resolve, reject)
  } else {
    originalPush.call(this, loaction, () => { }, () => { })
  }
}
VueRouter.prototype.replace = function (loaction, resolve, reject) {
  if (resolve && reject) {
    originalReplace.call(this, loaction, resolve, reject)
  } else {
    originalReplace.call(this, loaction, () => { }, () => { })
  }
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
  scrollBehavior (to, from, savedPosition) {
    // return 期望滚动到哪个的位置
    return { y: 0 }
  }
})

//当路由开始跳转时
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem("token")
  if(to.meta.needLogin) {
    if(!token) {
      store.dispatch("getUserInfo")
      return next(false);
    } else {
      store.dispatch("getUserInfo")
      // return next();
    }
  }
  // 如果用户登录了则不能去登录和注册页面
  if(token) {
    if(to.path == '/login' || to.path ==  '/register') {
      next(from.path)
    }
  }
  // 开启进度条
  nprogress.start();
  // 这个一定要加，没有next()页面不会跳转的。
  next();
});
//当路由跳转结束后
router.afterEach(() => {
  // 关闭进度条
  nprogress.done()
})

export default router
